import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/2;
 * Otherwise, I don't know who created it either
 */

public class Test03 {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        long startTime = System.currentTimeMillis();
        insertWithTrans();
        long endTime = System.currentTimeMillis();
        System.out.println("总耗时:"
                + (endTime - startTime) + "ms");
    }

    public static Connection getConn() {
        try {
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/lanou3",
                    "root",
                    "123456"
            );
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 总耗时:1220ms
    public static void insertWithTrans() {
        Connection conn = getConn();
        String sql = "INSERT INTO bank (cname, money) " +
                "VALUES (?,100)";
        try {
            // 开启事务
            conn.setAutoCommit(false);
            PreparedStatement statement
                    = conn.prepareStatement(sql);
            for (int i = 0; i < 100000; i++) {
                System.out.println("这是第: " + i + "次插入");
                statement.setString(1, "NAME-" + i);
                statement.executeUpdate();
            }
            statement.close();
            conn.commit();// 提交事务
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //22374ms 22.3s
    public static void insertNormal() {
        Connection conn = getConn();
        String sql = "INSERT INTO bank (cname, money) " +
                "VALUES (?,100)";
        for (int i = 0; i < 10000; i++) {
            System.out.println("这是第: " + i + "次插入");
            try {
                PreparedStatement statement =
                        conn.prepareStatement(sql);
                statement.setString(1,
                        "name-" + i);
                statement.executeUpdate();//执行
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 一定要放在for 结束之后
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
